package cn.harry.cabinet.utils

import android.content.Context
import android.graphics.Color
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import cn.harry.cabinet.R
import cn.harry.cabinet.theme.manager.ThemeManager

/**
 * 颜色工具类
 * 提供语义化颜色获取、颜色管理和颜色操作功能
 * 
 * 特性：
 * - 语义化颜色获取 (Success, Warning, Danger, Info, Neutral)
 * - 主题适配颜色获取
 * - 颜色透明度调整
 * - 颜色亮度计算
 * - 颜色对比度计算
 */
object ColorUtils {
    
    /**
     * 语义化颜色类型枚举
     */
    enum class SemanticColorType {
        SUCCESS,
        WARNING, 
        DANGER,
        INFO,
        NEUTRAL,
        PRIMARY
    }
    
    /**
     * 颜色变体枚举
     */
    enum class ColorVariant {
        DEFAULT,        // 默认颜色
        DARK,          // 深色变体
        LIGHT,         // 浅色变体
        BACKGROUND,    // 背景色
        TEXT,          // 文本色
        BORDER         // 边框色
    }
    
    /**
     * 获取语义化颜色
     * @param context 上下文
     * @param type 颜色类型
     * @param variant 颜色变体
     * @param isDarkMode 是否为深色模式
     * @return 颜色值
     */
    @ColorInt
    fun getSemanticColor(
        context: Context,
        type: SemanticColorType,
        variant: ColorVariant = ColorVariant.DEFAULT,
        isDarkMode: Boolean = false
    ): Int {
        val colorRes = getSemanticColorResource(context, type, variant, isDarkMode)
        return ContextCompat.getColor(context, colorRes)
    }
    
    /**
     * 获取语义化颜色资源ID
     */
    @ColorRes
    private fun getSemanticColorResource(
        context: Context,
        type: SemanticColorType,
        variant: ColorVariant,
        isDarkMode: Boolean
    ): Int {
        return when (type) {
            SemanticColorType.SUCCESS -> when (variant) {
                ColorVariant.DEFAULT -> R.color.semantic_success
                ColorVariant.DARK -> R.color.semantic_success_dark
                ColorVariant.LIGHT -> R.color.semantic_success_light
                ColorVariant.BACKGROUND -> if (isDarkMode) R.color.semantic_success_background_dark else R.color.semantic_success_background
                ColorVariant.TEXT -> if (isDarkMode) R.color.semantic_success_text_dark else R.color.semantic_success_text
                ColorVariant.BORDER -> R.color.semantic_success_border
            }
            
            SemanticColorType.WARNING -> when (variant) {
                ColorVariant.DEFAULT -> R.color.semantic_warning
                ColorVariant.DARK -> R.color.semantic_warning_dark
                ColorVariant.LIGHT -> R.color.semantic_warning_light
                ColorVariant.BACKGROUND -> if (isDarkMode) R.color.semantic_warning_background_dark else R.color.semantic_warning_background
                ColorVariant.TEXT -> if (isDarkMode) R.color.semantic_warning_text_dark else R.color.semantic_warning_text
                ColorVariant.BORDER -> R.color.semantic_warning_border
            }
            
            SemanticColorType.DANGER -> when (variant) {
                ColorVariant.DEFAULT -> R.color.semantic_danger
                ColorVariant.DARK -> R.color.semantic_danger_dark
                ColorVariant.LIGHT -> R.color.semantic_danger_light
                ColorVariant.BACKGROUND -> if (isDarkMode) R.color.semantic_danger_background_dark else R.color.semantic_danger_background
                ColorVariant.TEXT -> if (isDarkMode) R.color.semantic_danger_text_dark else R.color.semantic_danger_text
                ColorVariant.BORDER -> R.color.semantic_danger_border
            }
            
            SemanticColorType.INFO -> when (variant) {
                ColorVariant.DEFAULT -> R.color.semantic_info
                ColorVariant.DARK -> R.color.semantic_info_dark
                ColorVariant.LIGHT -> R.color.semantic_info_light
                ColorVariant.BACKGROUND -> if (isDarkMode) R.color.semantic_info_background_dark else R.color.semantic_info_background
                ColorVariant.TEXT -> if (isDarkMode) R.color.semantic_info_text_dark else R.color.semantic_info_text
                ColorVariant.BORDER -> R.color.semantic_info_border
            }
            
            SemanticColorType.NEUTRAL -> when (variant) {
                ColorVariant.DEFAULT -> R.color.neutral_500
                ColorVariant.DARK -> R.color.neutral_700
                ColorVariant.LIGHT -> R.color.neutral_300
                ColorVariant.BACKGROUND -> if (isDarkMode) R.color.neutral_background_dark else R.color.neutral_background
                ColorVariant.TEXT -> if (isDarkMode) R.color.neutral_text_primary_dark else R.color.neutral_text_primary
                ColorVariant.BORDER -> if (isDarkMode) R.color.neutral_border_dark else R.color.neutral_border
            }
            
            SemanticColorType.PRIMARY -> {
                // 获取当前主题的主色
                val currentTheme = ThemeManager.getCurrentTheme(context)
                when (currentTheme) {
                    ThemeManager.Theme.CHINA_RED -> when (variant) {
                        ColorVariant.DEFAULT -> R.color.china_red_primary
                        ColorVariant.DARK -> R.color.china_red_primary_dark
                        ColorVariant.LIGHT -> R.color.china_red_primary_light
                        ColorVariant.BACKGROUND -> R.color.china_red_background
                        ColorVariant.TEXT -> R.color.china_red_on_primary
                        ColorVariant.BORDER -> R.color.china_red_divider
                    }
                    ThemeManager.Theme.VIBRANT_ORANGE -> when (variant) {
                        ColorVariant.DEFAULT -> R.color.vibrant_orange_primary
                        ColorVariant.DARK -> R.color.vibrant_orange_primary_dark
                        ColorVariant.LIGHT -> R.color.vibrant_orange_primary_light
                        ColorVariant.BACKGROUND -> R.color.vibrant_orange_background
                        ColorVariant.TEXT -> R.color.vibrant_orange_on_primary
                        ColorVariant.BORDER -> R.color.vibrant_orange_divider
                    }
                    ThemeManager.Theme.TECH_BLUE -> when (variant) {
                        ColorVariant.DEFAULT -> R.color.tech_blue_primary
                        ColorVariant.DARK -> R.color.tech_blue_primary_dark
                        ColorVariant.LIGHT -> R.color.tech_blue_primary_light
                        ColorVariant.BACKGROUND -> R.color.tech_blue_background
                        ColorVariant.TEXT -> R.color.tech_blue_on_primary
                        ColorVariant.BORDER -> R.color.tech_blue_divider
                    }
                }
            }
        }
    }
    
    /**
     * 获取中性色
     * @param context 上下文
     * @param shade 色阶 (50-900)
     * @return 颜色值
     */
    @ColorInt
    fun getNeutralColor(context: Context, shade: Int): Int {
        val colorRes = when (shade) {
            50 -> R.color.neutral_50
            100 -> R.color.neutral_100
            200 -> R.color.neutral_200
            300 -> R.color.neutral_300
            400 -> R.color.neutral_400
            500 -> R.color.neutral_500
            600 -> R.color.neutral_600
            700 -> R.color.neutral_700
            800 -> R.color.neutral_800
            900 -> R.color.neutral_900
            else -> R.color.neutral_500 // 默认使用500
        }
        return ContextCompat.getColor(context, colorRes)
    }
    
    /**
     * 获取主题适配的语义化颜色
     * @param context 上下文
     * @param type 颜色类型
     * @param variant 颜色变体
     * @return 颜色值
     */
    @ColorInt
    fun getThemeSemanticColor(
        context: Context,
        type: SemanticColorType,
        variant: ColorVariant = ColorVariant.DEFAULT
    ): Int {
        val colorRes = when (type) {
            SemanticColorType.SUCCESS -> when (variant) {
                ColorVariant.DEFAULT -> R.color.theme_success
                ColorVariant.DARK -> R.color.theme_success_dark
                ColorVariant.LIGHT -> R.color.theme_success_light
                ColorVariant.BACKGROUND -> R.color.theme_success_background
                ColorVariant.TEXT -> R.color.theme_success_text
                else -> R.color.theme_success
            }
            SemanticColorType.WARNING -> when (variant) {
                ColorVariant.DEFAULT -> R.color.theme_warning
                ColorVariant.DARK -> R.color.theme_warning_dark
                ColorVariant.LIGHT -> R.color.theme_warning_light
                ColorVariant.BACKGROUND -> R.color.theme_warning_background
                ColorVariant.TEXT -> R.color.theme_warning_text
                else -> R.color.theme_warning
            }
            SemanticColorType.DANGER -> when (variant) {
                ColorVariant.DEFAULT -> R.color.theme_danger
                ColorVariant.DARK -> R.color.theme_danger_dark
                ColorVariant.LIGHT -> R.color.theme_danger_light
                ColorVariant.BACKGROUND -> R.color.theme_danger_background
                ColorVariant.TEXT -> R.color.theme_danger_text
                else -> R.color.theme_danger
            }
            SemanticColorType.INFO -> when (variant) {
                ColorVariant.DEFAULT -> R.color.theme_info
                ColorVariant.DARK -> R.color.theme_info_dark
                ColorVariant.LIGHT -> R.color.theme_info_light
                ColorVariant.BACKGROUND -> R.color.theme_info_background
                ColorVariant.TEXT -> R.color.theme_info_text
                else -> R.color.theme_info
            }
            SemanticColorType.NEUTRAL -> when (variant) {
                ColorVariant.DEFAULT -> R.color.theme_neutral
                ColorVariant.DARK -> R.color.theme_neutral_dark
                ColorVariant.LIGHT -> R.color.theme_neutral_light
                ColorVariant.BACKGROUND -> R.color.theme_neutral_background
                ColorVariant.TEXT -> R.color.theme_neutral_text
                else -> R.color.theme_neutral
            }
            SemanticColorType.PRIMARY -> when (variant) {
                ColorVariant.DEFAULT -> R.color.theme_primary
                ColorVariant.DARK -> R.color.theme_primary_dark
                ColorVariant.LIGHT -> R.color.theme_primary_light
                ColorVariant.BACKGROUND -> R.color.theme_background
                ColorVariant.TEXT -> R.color.theme_on_primary
                else -> R.color.theme_primary
            }
        }
        return ContextCompat.getColor(context, colorRes)
    }
    
    /**
     * 调整颜色透明度
     * @param color 原始颜色
     * @param alpha 透明度 (0.0-1.0)
     * @return 调整后的颜色
     */
    @ColorInt
    fun adjustAlpha(@ColorInt color: Int, alpha: Float): Int {
        val alphaInt = (255 * alpha.coerceIn(0f, 1f)).toInt()
        return Color.argb(alphaInt, Color.red(color), Color.green(color), Color.blue(color))
    }
    
    /**
     * 计算颜色亮度
     * @param color 颜色值
     * @return 亮度值 (0.0-1.0)
     */
    fun getLuminance(@ColorInt color: Int): Double {
        val red = Color.red(color) / 255.0
        val green = Color.green(color) / 255.0
        val blue = Color.blue(color) / 255.0
        
        val r = if (red <= 0.03928) red / 12.92 else Math.pow((red + 0.055) / 1.055, 2.4)
        val g = if (green <= 0.03928) green / 12.92 else Math.pow((green + 0.055) / 1.055, 2.4)
        val b = if (blue <= 0.03928) blue / 12.92 else Math.pow((blue + 0.055) / 1.055, 2.4)
        
        return 0.2126 * r + 0.7152 * g + 0.0722 * b
    }
    
    /**
     * 计算两个颜色的对比度
     * @param color1 第一个颜色
     * @param color2 第二个颜色
     * @return 对比度比值 (1-21)
     */
    fun getContrastRatio(@ColorInt color1: Int, @ColorInt color2: Int): Double {
        val luminance1 = getLuminance(color1)
        val luminance2 = getLuminance(color2)
        val lighter = Math.max(luminance1, luminance2)
        val darker = Math.min(luminance1, luminance2)
        return (lighter + 0.05) / (darker + 0.05)
    }
    
    /**
     * 检查颜色对比度是否符合无障碍标准
     * @param foregroundColor 前景色
     * @param backgroundColor 背景色
     * @param level AA级别 (AA: 4.5, AAA: 7.0)
     * @return 是否符合标准
     */
    fun isAccessibilityCompliant(
        @ColorInt foregroundColor: Int,
        @ColorInt backgroundColor: Int,
        level: String = "AA"
    ): Boolean {
        val contrastRatio = getContrastRatio(foregroundColor, backgroundColor)
        val requiredRatio = when (level.uppercase()) {
            "AAA" -> 7.0
            else -> 4.5 // AA
        }
        return contrastRatio >= requiredRatio
    }
    
    /**
     * 根据背景色自动选择最佳文本颜色
     * @param backgroundColor 背景色
     * @return 最佳文本颜色（黑色或白色）
     */
    @ColorInt
    fun getBestTextColor(@ColorInt backgroundColor: Int): Int {
        val luminance = getLuminance(backgroundColor)
        return if (luminance > 0.5) Color.BLACK else Color.WHITE
    }
    
    /**
     * 混合两个颜色
     * @param color1 第一个颜色
     * @param color2 第二个颜色
     * @param ratio 混合比例 (0.0-1.0，0.0表示完全是color1，1.0表示完全是color2)
     * @return 混合后的颜色
     */
    @ColorInt
    fun blendColors(@ColorInt color1: Int, @ColorInt color2: Int, ratio: Float): Int {
        val inverseRatio = 1f - ratio
        val r = (Color.red(color1) * inverseRatio + Color.red(color2) * ratio).toInt()
        val g = (Color.green(color1) * inverseRatio + Color.green(color2) * ratio).toInt()
        val b = (Color.blue(color1) * inverseRatio + Color.blue(color2) * ratio).toInt()
        val a = (Color.alpha(color1) * inverseRatio + Color.alpha(color2) * ratio).toInt()
        return Color.argb(a, r, g, b)
    }
    
    /**
     * 将颜色转换为十六进制字符串
     * @param color 颜色值
     * @param includeAlpha 是否包含透明度
     * @return 十六进制字符串
     */
    fun colorToHex(@ColorInt color: Int, includeAlpha: Boolean = false): String {
        return if (includeAlpha) {
            String.format("#%08X", color)
        } else {
            String.format("#%06X", 0xFFFFFF and color)
        }
    }
    
    /**
     * 从十六进制字符串解析颜色
     * @param hex 十六进制字符串 (如 "#FF0000" 或 "#FFFF0000")
     * @return 颜色值
     */
    @ColorInt
    fun parseColor(hex: String): Int {
        return try {
            Color.parseColor(hex)
        } catch (e: IllegalArgumentException) {
            Color.TRANSPARENT
        }
    }
}